package Middlewares

import (
	"AI/sql/disposition"
	status "AI/util"

	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"
	"slices"
	"strings"

	"github.com/gin-gonic/gin"
)

func init() {

}

type balance struct {
	Account string
}

// 写一个中间件，统计视图函数运行时间
func TotalTime(c *gin.Context) {
	// 解决跨域问题
	c.Header("Access-Control-Allow-Origin", "*")
	c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
	c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
	c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
	c.Header("Access-Control-Allow-Credentials", "true")
	//这里是解决vue那个坑
	method := c.Request.Method
	c.Set("status", 200)
	if method == "OPTIONS" {
		c.AbortWithStatus(http.StatusNoContent)
	}
	// 白名单
	if slices.Contains(status.Whitelist, c.FullPath()) {
		c.Next()
		return
	}

	// 判断请求头中是否有token
	aut := c.Request.Header.Get("Authorization")
	ok := strings.HasPrefix(aut, "Bearer")
	// fmt.Println(aut)
	if aut == "" || !ok {
		c.Set("status", 401)
		c.Set("islogin", false)
		c.Abort()
		c.JSON(http.StatusOK, gin.H{
			"code": status.Exit,
			"msg":  "err",
			"data": "请重新登录,谢谢!",
		})
		return
	}
	token := string([]byte(aut)[strings.Index(aut, "-")+2:])
	// fmt.Println(token)
	if token == "Err" {
		c.Set("status", 401)
		c.Set("islogin", false)
		c.Abort()
		c.JSON(http.StatusOK, gin.H{
			"code": status.Exit,
			"msg":  "err",
			"data": "非法登录,您的账号已被封禁!",
		})
		return
	}
	// 根据token查账号
	sqls := fmt.Sprintf(`select Account from userinfo where token = "%s"`, token)
	// fmt.Println(sqls)
	db, _ := sql.Open(disposition.Usersql["sqlname"], disposition.Usersql["sqlurl"])

	info, _ := db.Query(sqls)

	var Account balance
	if !info.Next() {
		c.Abort()
		c.JSON(http.StatusOK, gin.H{
			"code": status.Exit,
			"msg":  "err",
			"data": "登录信息过期,请重新登录谢谢",
		})
		return
	}
	_ = info.Scan(&Account.Account)
	Data := make(map[string]string)
	json.NewDecoder(c.Request.Body).Decode(&Data)
	if Data["Account"] != Account.Account {
		// fmt.Println(Data)

		// 操作数据库
		sqls = fmt.Sprintf(`UPDATE userinfo SET token="Err",status=0 where Account = "%s" `, Account.Account)
		// fmt.Println(sqls)
		db.Exec(sqls)
		c.Abort()
		c.JSON(http.StatusOK, gin.H{
			"code": status.Illegal,
			"msg":  "err",
			"data": "非法登录,该账号已被封禁",
		})

		return
	}
	defer db.Close()
	c.Set("token", token)
	c.Set("Account", Account.Account)
	for key := range Data {
		c.Set(key, Data[key])
	}
	c.Next()
}
